<template>
	<view>
		<!-- <Tabs :tabsList="tabsList" @tabItem="getTabs"></Tabs> -->
		<form>
			<view class="cu-form-group">
				<view class="title">昵称</view>
				<input type="nickname" name="nickname" @blur="bindNickname" v-model="nick_name"></input>
			</view>
			<view class="cu-form-group">
				<view class="title">头像</view>
				<view class="bg-img" @tap="ChooseAvatar">
					<button open-type="chooseAvatar" @chooseavatar="onChooseAvatar"
						style="padding:0;max-width:50px;max-height:50px;">
						<image class="avatar" :src="avatar" style="max-width:50px;max-height:50px;"></image>
						<input name="avatar" :value="avatar" style="display: none;" />
					</button>
				</view>
			</view>
			<!-- <view class="cu-bar bg-white margin-top">
				<view class="action">
					头像
				</view>
			</view>
			<view class="cu-form-group">
				<view class="grid col-4 grid-square flex-sub">
					<image :src="avatar" mode="aspectFit"></image>
					<button class="solids" open-type="chooseAvatar" @chooseavatar="onChooseAvatar" v-if="avatar == ''">
						<text class='cuIcon-cameraadd'></text>
					</button>
				</view>
			</view> -->
			<view class="cu-form-group">
				<view class="title">性别</view>
				<picker @change="PickerGender" v-model="gender_index" :range="gender">
					<view class="picker">
						{{gender_index>-1?gender[gender_index]:'男'}}
					</view>
				</picker>
			</view>
			<view class="cu-form-group">
				<view class="title">出生日期</view>
				<picker mode="date" v-model="birthday" start="1990-09-01" end="2020-09-01" @change="birthdayChange">
					<view class="picker">
						{{birthday}}
					</view>
				</picker>
			</view>
			<!-- <view class="cu-form-group">
				<view class="title">所在位置</view>
				<picker mode="region" @change="RegionChange" v-model="region">
					<view class="picker">
						{{region[0]}}，{{region[1]}}，{{region[2]}}
					</view>
				</picker>
			</view> -->
			<view class="cu-form-group">
				<view class="title">所在位置</view>
				<pick-regions :defaultRegion="region" @getRegion="handleGetRegion">
					<view class="picker">
						{{region[0]}}，{{region[1]}}，{{region[2]}}
					</view>
				</pick-regions>
			</view>
			<view class="cu-form-group">
				<view class="title">身高</view>
				<uv-input placeholder="请输您的身高" border="none" v-model="heights" type="number" inputAlign="right">
					<template v-slot:suffix>
						<text>cm</text>
					</template>


				</uv-input>
				<!-- 		<picker @change="heightChange" v-model="height_index" :range="heights">
					<view class="picker">
						{{height_index>-1?heights[height_index]:'170'}}
					</view>
				</picker> -->
			</view>
			<view class="cu-form-group">
				<view class="title">体重</view>
				<uv-input placeholder="请输您的体重" border="none" v-model="weights" type="number" inputAlign="right">
					<template v-slot:suffix>
						<text>kg</text>
					</template>


				</uv-input>
				<!-- 	<picker @change="weightChange" v-model="weight_index" :range="weights">
					<view class="picker">
						{{weight_index>-1?weights[weight_index]:'55kg'}}
					</view>
				</picker> -->
			</view>
			<view class="cu-form-group">
				<view class="title">学历</view>
				<picker @change="degreeChange" v-model="degree_index" :range="degrees">
					<view class="picker">
						{{degree_index>-1?degrees[degree_index]:'大专'}}
					</view>
				</picker>
			</view>
			<view class="cu-form-group">
				<view class="title">收入(年薪)</view>
				<picker @change="incomeChange" v-model="income_index" :range="incomes">
					<view class="picker">
						{{income_index>-1?incomes[income_index]:'5万-10万'}}
					</view>
				</picker>
			</view>
			<view class="cu-form-group">
				<!-- <view class="title">小红书号</view> -->
				<view class="title">微信号</view>
				<input name="input" v-model="red_book_id"></input>
			</view>
			<view class="cu-form-group">
				<view class="title">性格</view>
				<input name="input" v-model="character"></input>
			</view>
			<view class="cu-form-group">
				<view class="title">爱好</view>
				<input name="input" v-model="hobby"></input>
			</view>
			<!-- <view class="cu-form-group">
				<view class="title">手机号码</view>
				<input name="input" v-model="phone"></input>
				<view class="cu-capsule radius">
					<view class='cu-tag bg-blue '>
						+86
					</view>
					<view class="cu-tag line-blue">
						中国大陆
					</view>
				</view>
			</view> -->
			<view class="cu-bar bg-white">
				<view class="action">
					生活照片
				</view>
				<view class="action">
					{{photos.length}}/4
				</view>
			</view>
			<view class="cu-form-group">
				<view class="grid col-4 grid-square flex-sub">
					<view class="bg-img" v-for="(item,index) in photos" :key="index" @tap="ViewImage"
						:data-url="photos[index]">
						<image :src="photos[index]" mode="aspectFill"></image>
						<view class="cu-tag bg-red" @tap.stop="DelImg" :data-index="index">
							<text class='cuIcon-close'></text>
						</view>
					</view>
					<view class="solids" @tap="ChooseImage" v-if="photos.length<4">
						<text class='cuIcon-cameraadd'></text>
					</view>
				</view>
			</view>
			<!-- <view class="cu-form-group margin-top">
				<view class="title">是否展示照片</view>
				<switch @change="SwitchShowPhoto" :class="switch_show_photo?'checked':''" :checked="switch_show_photo?true:false"></switch>
			</view> -->
			<view class="cu-form-group align-start">
				<view class="title">对另一半期望</view>
				<textarea maxlength="-1" :disabled="modalName!=null" @input="otherExpectInput"
					v-model="other_expect"></textarea>
			</view>
			<view class="cu-item" v-if="status == 2">
				<view class="content">
					<text class="cuIcon-title text-orange"></text>
					未通过原因: <text class="text-red padding-left">{{audit_expect}}</text>
				</view>
			</view>
			<view class="padding flex flex-direction">
				<button class="cu-btn bg-grey lg" @click="saveProfile">保存</button>
			</view>
		</form>
	</view>
</template>

<script>
	import Compressor from 'compressorjs';
	import pickRegions from '@/components/pick-regions/pick-regions.vue'
	import {
		profileInfo,
		editProfile
	} from '../../api/account';
	import {
		apiUrl
	} from '../../config/server.config';
	// import Tabs from "../component/tabs.vue"
	export default {
		components: {
			pickRegions,
			// Tabs
		},
		data() {
			return {
				// tabsList: [{
				// 	name: '个人资料'
				// }, {
				// 	name: '对另一半期望'
				// }],
				region: ['广东省', '广州市', '海珠区'],
				// defaultRegion:['广东省','广州市','番禺区'],
				// defaultRegionCode:'440113',
				nick_name: '',
				avatar: '',
				gender: ['男', '女'],
				gender_index: 0,
				birthday: '2000-12-25',
				// region: ['广东省', '广州市', '海珠区'],

				weights: 0,
				heights: 0,
				degrees: ['小学', '初中', '高中', '大专', '本科', '硕士', '博士'],
				degree_index: 3,
				incomes: ['5万以下', '5万-10万', '10万-15万', '15万-20万', '20万-30万', '30-40万', '40-50万', '50-100万', '100万以上'],
				income_index: 0,
				red_book_id: '',
				character: '',
				hobby: '',
				phone: '',
				photos: [],
				switch_show_photo: true,
				modalName: null,
				other_expect: '',
				audit_expect: '',
				status: 1,
			};
		},
		onLoad() {
			// 获取个人资料
			profileInfo().then(res => {
				if (res.nick_name == undefined) {
					return
				}
				if (res.nick_name != undefined) {
					this.nick_name = res.nick_name
				}
				this.avatar = res.avatar
				const gender_index = this.gender.indexOf(res.gender)
				if (gender_index !== -1) {
					this.gender_index = gender_index
				}

				this.birthday = res.birthday
				this.region = res.region

				const degree_index = this.degrees.indexOf(res.degree)
				if (degree_index !== -1) {
					this.degree_index = degree_index
				}
				const income_index = this.incomes.indexOf(res.income)
				if (income_index !== -1) {
					this.income_index = income_index
				}
				this.red_book_id = res.red_book_id
				this.character = res.character
				this.hobby = res.hobby
				this.phone = res.phone
				this.photos = res.photos
				this.switch_show_photo = res.switch_show_photo
				this.other_expect = res.other_expect
				this.audit_expect = res.audit_expect
				this.status = res.status
			}).catch(err => {
				console.log(err)
			});
		},
		methods: {
			// // 图片压缩函数
			//  compressImg (file) {
			//    const that = this
			//    var files
			//    var fileSize = parseFloat(parseInt(file['size']) / 1024 / 1024).toFixed(2)
			//    var read = new FileReader()
			//    read.readAsDataURL(file)
			//    return new Promise(function (resolve, reject) {
			//      read.onload = function (e) {
			//        var img = new Image()
			//        img.src = e.target.result
			//        img.onload = function () {
			//          // 默认按比例压缩
			//          var w = this.width
			//          var h = this.height
			//          // 生成canvas
			//          var canvas = document.createElement('canvas')
			//          var ctx = canvas.getContext('2d')
			//          var base64
			//          // 创建属性节点
			//          canvas.setAttribute('width', w)
			//          canvas.setAttribute('height', h)
			//          ctx.drawImage(this, 0, 0, w, h)
			//          if (fileSize < 1) {
			//            // 如果图片小于一兆 那么压缩0.5
			//            base64 = canvas.toDataURL(file['type'], 0.5)
			//          } else if (fileSize > 1 && fileSize < 2) {
			//            // 如果图片大于1M并且小于2M 那么压缩0.5
			//            base64 = canvas.toDataURL(file['type'], 0.5)
			//          } else {
			//            // 如果图片超过2m 那么压缩0.2
			//            base64 = canvas.toDataURL(file['type'], 0.2)
			//          }
			//          // 回调函数返回file的值（将base64编码转成file）
			//          files = that.dataURLtoFile(base64, file.name) // 如果后台接收类型为base64的话这一步可以省略
			//          resolve(files)
			//        }
			//      }
			//    })
			//  },
			//   // base64转码（压缩完成后的图片为base64编码，这个方法可以将base64编码转回file文件）
			//   dataURLtoFile (dataurl, filename) {
			//     var arr = dataurl.split(',')
			//     var mime = arr[0].match(/:(.*?);/)[1]
			//     var bstr = atob(arr[1])
			//     var n = bstr.length
			//     var u8arr = new Uint8Array(n)
			//     while (n--) {
			//       u8arr[n] = bstr.charCodeAt(n)
			//     }
			//     return new File([u8arr], filename, { type: mime })
			//   },
			// 获取选择的地区
			handleGetRegion(region) {
				this.region = region.map(item => item.name)
			},
			ChooseAvatar() {
				console.log("上传头像")
				uni.chooseImage({
					count: 1, //默认9
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album'], //从相册选择
					success: (res) => {
						//图片压缩
						new Compressor(res.tempFiles[0], {
							quality: 0.6, // 压缩质量
							convertSize: false,
							success: (result) => {
								//这里是Bold流转化为新的File
								const fileA = new File([result], result.name, {
									type: result.type
								})
								//这里写压缩后的主逻辑
								let fileUrl = window.URL.createObjectURL(fileA)
								uni.uploadFile({
									url: apiUrl + '/upload_file',
									filePath: fileUrl, // 要上传文件资源的路径
									name: 'file', // 文件对应的 key
									header: {
										'Authorization': uni.getStorageSync('token')
									},
									success: uploadRes => {
										// 处理上传成功的结果
										console.log('upload success:', uploadRes.data);
										var data = JSON.parse(uploadRes.data)
										this.avatar = data.file_name
									},
									fail: uploadError => {
										// 处理上传失败的错误
										console.error('upload error:', uploadError);
										uni.showToast({
											title: '照片上传失败',
											icon: 'none'
										});
									}
								})
							},
							error: (error) => {
								console.error('图片压缩失败', error);
							},
						});

						// uni.uploadFile({
						// 	url: apiUrl + '/upload_file',
						// 	filePath: res.tempFilePaths[0], // 要上传文件资源的路径
						// 	name: 'file', // 文件对应的 key
						// 	header: {
						// 		'Authorization': uni.getStorageSync('token')
						// 	},
						// 	success: uploadRes => {
						// 		// 处理上传成功的结果
						// 		console.log('upload success:', uploadRes.data);
						// 		var data = JSON.parse(uploadRes.data)
						// 		this.avatar = apiUrl + data.file_name
						// 	},
						// 	fail: uploadError => {
						// 		// 处理上传失败的错误
						// 		console.error('upload error:', uploadError);
						// 		uni.showToast({ title: '照片上传失败', icon: 'none' });
						// 	}
						// })
					}
				});
			},
			// onChooseAvatar(e) {
			// 	console.log("上传头像2")
			// 	uni.uploadFile({
			// 		url: apiUrl + '/upload_file',
			// 		filePath: e.detail.avatarUrl, // 要上传文件资源的路径
			// 		name: 'file', // 文件对应的 key
			// 		header: {
			// 			'Authorization': uni.getStorageSync('token')
			// 		},
			// 		success: uploadRes => {
			// 			// 处理上传成功的结果
			// 			console.log('upload success:', uploadRes.data);
			// 			var data = JSON.parse(uploadRes.data)
			// 			this.avatar = data.file_name
			// 		},
			// 		fail: uploadError => {
			// 			// 处理上传失败的错误
			// 			console.error('upload error:', uploadError);
			// 			uni.showToast({ title: '照片上传失败', icon: 'none' });
			// 		}
			// 	})

			//     // this.http.post(this.$url.file.uploadBase64Img, {data: reqData, showLoading: false}).then(res => {
			//     //         if(res.code === 200){
			//     //            this.defaultAvatar = res.data;
			//     //         } else{
			//     //            this.tui.toast(res.message);
			//     //         }
			//     // }).catch(e => {
			//     //         console.log(e)
			//     // })
			// },
			bindNickname(e) {
				// 绑定昵称
				this.nick_name = e.detail.value
			},
			PickerGender(e) {
				// 选择性别
				this.gender_index = e.detail.value
			},
			birthdayChange(e) {
				// 选择生日
				this.birthday = e.detail.value
			},
			// RegionChange(e) {
			// 	// 选择所在位置
			// 	this.region = e.detail.value
			// },


			degreeChange(e) {
				// 选择学历
				this.degree_index = e.detail.value
			},
			incomeChange(e) {
				// 选择年薪
				this.income_index = e.detail.value
			},
			SwitchShowPhoto(e) {
				this.switch_show_photo = e.detail.value
			},
			ChooseImage() {
				console.log("上传生活照片")
				uni.chooseImage({
					count: 4, //默认9
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album'], //从相册选择
					success: (res) => {
						// uni.uploadFile({
						// 	url: apiUrl + '/upload_file',
						// 	filePath: res.tempFilePaths[0], // 要上传文件资源的路径
						// 	name: 'file', // 文件对应的 key
						// 	header: {
						// 		'Authorization': uni.getStorageSync('token')
						// 	},
						// 	success: uploadRes => {
						// 		// 处理上传成功的结果
						// 		console.log('upload success:', uploadRes.data);
						// 		var data = JSON.parse(uploadRes.data)
						// 		this.photos.push(data.file_name)
						// 	},
						// 	fail: uploadError => {
						// 		// 处理上传失败的错误
						// 		console.error('upload error:', uploadError);
						// 		uni.showToast({ title: '照片上传失败', icon: 'none' });
						// 	}
						// })

						for (var i = 0; i < res.tempFiles.length; i++) {
							//图片压缩
							new Compressor(res.tempFiles[i], {
								quality: 0.6, // 压缩质量
								convertSize: false,
								success: (result) => {
									//这里是Bold流转化为新的File
									const fileA = new File([result], result.name, {
										type: result.type
									})
									//这里写压缩后的主逻辑
									let fileUrl = window.URL.createObjectURL(fileA)
									uni.uploadFile({
										url: apiUrl + '/upload_file',
										filePath: fileUrl, // 要上传文件资源的路径
										name: 'file', // 文件对应的 key
										header: {
											'Authorization': uni.getStorageSync('token')
										},
										success: uploadRes => {
											// 处理上传成功的结果
											console.log('upload success:', uploadRes
												.data);
											var data = JSON.parse(uploadRes.data)
											this.photos.push(data.file_name)
										},
										fail: uploadError => {
											// 处理上传失败的错误
											console.error('upload error:',
											uploadError);
											uni.showToast({
												title: '照片上传失败',
												icon: 'none'
											});
										}
									})
								},
								error: (error) => {
									console.error('图片压缩失败', error);
								},
							});
						}
					}
				});
			},
			ViewImage(e) {
				uni.previewImage({
					urls: this.photos,
					current: e.currentTarget.dataset.url
				});
			},
			DelImg(e) {
				uni.showModal({
					title: '亲爱的用户',
					content: '确定要删除这张照片？',
					cancelText: '取消',
					confirmText: '确认',
					success: res => {
						if (res.confirm) {
							this.photos.splice(e.currentTarget.dataset.index, 1)
						}
					}
				})
			},
			otherExpectInput(e) {
				// 对另一半期望
				this.other_expect = e.detail.value
			},
			saveProfile() {
				// console.log(this.tool.isValidPhoneNumber(18579250335))
				// 保存资料
				if (!this.tool.checkNickname(this.nick_name)) {
					uni.showToast({
						title: '请填写合法昵称',
						icon: 'none'
					});
					return
				}
				if (this.avatar.trim() === '') {
					uni.showToast({
						title: '请选择头像',
						icon: 'none'
					});
					return
				}
				if (this.red_book_id.trim() === '') {
					uni.showToast({
						title: '请填写小红书号',
						icon: 'none'
					});
					return
				}
				if (this.character.trim() === '') {
					uni.showToast({
						title: '请填写性格',
						icon: 'none'
					});
					return
				}
				if (this.hobby.trim() === '') {
					uni.showToast({
						title: '请填写爱好',
						icon: 'none'
					});
					return
				}
				if (this.character.trim() === '') {
					uni.showToast({
						title: '请填写性格',
						icon: 'none'
					});
					return
				}
				// if (!this.tool.isValidPhoneNumber(this.phone)) {
				// 	uni.showToast({ title: '请填写合法手机号', icon: 'none' });
				// 	return
				// }
				if (this.photos.length == 0) {
					uni.showToast({
						title: '至少上传一张生活照',
						icon: 'none'
					});
					return
				}
				if (this.other_expect.trim() === '') {
					uni.showToast({
						title: '请填写对另一半期望',
						icon: 'none'
					});
					return
				}
				// console.log(this.nickname)
				// console.log(this.gender[this.gender_index])
				// console.log(this.birthday)
				// console.log(this.region)
				// console.log(this.heights[this.height_index])
				// console.log(this.weights[this.weight_index])
				// console.log(this.incomes[this.income_index])
				// console.log(this.character)
				// console.log(this.hobby)
				// console.log(this.phone)
				// console.log(this.photos)
				// console.log(this.SwitchShowPhoto)
				// console.log(this.other_expect)

				var data = {
					nick_name: this.nick_name,
					avatar: this.avatar,
					gender: this.gender[this.gender_index],
					birthday: this.birthday,
					region: this.region,
					height: this.heights,
					weight: this.weights,
					degree: this.degrees[this.degree_index],
					income: this.incomes[this.income_index],
					red_book_id: this.red_book_id,
					character: this.character,
					hobby: this.hobby,
					phone: this.phone,
					photos: this.photos,
					switch_show_photo: this.switch_show_photo,
					other_expect: this.other_expect,
				}
				editProfile(data).then(res => {
					uni.showToast({
						title: '保存成功',
						icon: 'none'
					});
					// 跳转首页
					uni.navigateTo({
						url: '/pages/index/index' // 跳转到对应路径的页面
					});
				}).catch(err => {
					uni.showToast({
						title: '保存失败',
						icon: 'none'
					});
				});
			}
		}
	}
</script>

<style>
	.cu-form-group .title {
		min-width: calc(4em + 15px);
	}
</style>